package com.cluck.alipay.service.impl;

import com.cluck.alipay.entity.Order;
import com.cluck.alipay.repository.OrderRepository;
import com.cluck.alipay.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * 订单服务层实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public void save(Order order) {
        orderRepository.save(order);
    }

    @Override
    public Order getByOrOrderNo(String orderNo) {
        return orderRepository.findByOrOrderNo(orderNo);
    }

    @Override
    public Page<Order> list(Order order, Integer page, Integer size) {

        Pageable pageable = PageRequest.of(page-1, size, Sort.Direction.DESC, "buyTime");

        Page<Order> pageOrder = orderRepository.findAll(new Specification<Order>() {
            @Override
            public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                predicate.getExpressions().add(cb.equal(root.get("isPay"), 1));
                return predicate;
            }
        }, pageable);
        return pageOrder;
    }


}
